#ifndef _ACCEPTOR_HPP
#define _ACCEPTOR_HPP

#include "Reactor.hpp"
#include "Sock.hpp"
#include "Util.hpp"
#include "Server.hpp"

int Acceptor(Event* event)
{
  std::cout << "有新链接到来！" << std::endl;
  // 可能不止一个链接，所以需要循环读取，在ET模式下需要设置为非阻塞
  while(true)
  {
      // 这里不使用Sock封装的Accept，因为要处理返回值
      // int fd = Sock::Accept(event->_sock);
      struct sockaddr_in peer;
      bzero(&peer, sizeof(peer));
      socklen_t len = sizeof(peer);
      int fd = accept(event->_sock, reinterpret_cast<struct sockaddr*>(&peer), &(len));
      if(fd == -1)
      {
          fprintf(stderr, "读取新链接失败!\n");
          break;
      }

      // 获取成功
      Event* new_event = new Event;
      if(new_event == nullptr)
      {
          throw std::bad_alloc();
      }
      new_event->_sock = fd;
      new_event->_R = event->_R;
      new_event->RegisterCallback(Receive, Send, Error);
      // 怎么向Reactor添加柴火
      // 通过回指指针指向Reactor
      new_event->_R->InsertEvent(new_event, EPOLLIN | EPOLLET);
      // 设置为非阻塞
      SetNonBlock(fd);
      fprintf(stdout, "Add new event succed\n!");
  }

  return 0;
}

#endif

